package cn.dida.controller;

import cn.dida.exception.BizzException;
import cn.dida.model.*;
import cn.dida.service.BrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * <p>品牌管理</p>
 * @author weiwei
 * */
@Controller
public class BrandController extends BaseController {
    @Autowired
    private BrandService brandService;
    /**
     * 品牌列表
     * @param request
     * @param keyword 查询条件
     * @param state 状态（1：正常、2：已停用）
     * @param page 分页游标
     * @return ModelAndView 列表页面
     * @throws Exception
     */
    @GetMapping("/brand")
    public ModelAndView brand(HttpServletRequest request, String keyword, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        page = (page == null || page < 1) ? 1 : page;
        keyword = StringUtils.trimToNull(keyword);

        Pageable<Brand> brandList = brandService.queryBrand(userSession.getCompanyId(), keyword, state, page);
        model.put("brandList", brandList);
        model.put("keyword", keyword);
        model.put("state", state);
        return new ModelAndView("brand_list").addAllObjects(model);
    }
    
    /**
     * 品牌列表
     * @param request
     * @param keyword 查询条件
     * @param state 状态（1：正常、2：已停用）
     * @param page 分页游标
     * @return HttpResponseBodyWrapper 包装品牌列表数据List<Brand>
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "/brand", produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request, String keyword, Integer state, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        List<Brand> brandList = brandService.queryBrand(userSession.getCompanyId(), state);
        model.put("brandList", brandList);
        return new HttpResponseBodyWrapper(brandList);
    }

    /**
     * 新增品牌
     * @param request
     * @param brand 品牌实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/brand")
    public HttpResponseBodyWrapper postBrand(HttpServletRequest request, @RequestBody Brand brand) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        brand.setName(StringUtils.trimToNull(brand.getName()));
        brand.setCompanyId(userSession.getCompanyId());
        brand.setCreateStaffId(userSession.getId());

        if (brand.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入品牌名称");
        }
        if (brandService.getBrandByName(userSession.getCompanyId(), brand.getName()) != null) {
            throw new BizzException(BizzException.error_code_invalid_params, "已存在名为【" + brand.getName() + "】的品牌");
        }

        Boolean result = brandService.insertBrand(brand);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 根据公司id和品牌id获取品牌信息
     * @param id 品牌id
     * @return HttpResponseBodyWrapper 封装单个品牌实体数据
     * */
    @ResponseBody
    @GetMapping("/brand/{id}")
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request, @PathVariable Integer id) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        Brand result = brandService.getBrand(userSession.getCompanyId(), id);
        return new HttpResponseBodyWrapper(result);
    }
    /**
     * 更新品牌
     * @param brand 品牌实体信息
     * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
     * */
    @ResponseBody
    @PutMapping("/brand/{id}")
    public HttpResponseBodyWrapper putBrand(HttpServletRequest request, @RequestBody Brand brand) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);

        brand.setName(StringUtils.trimToNull(brand.getName()));
        brand.setCompanyId(userSession.getCompanyId());
        if (brand.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入品牌名称");
        }

        Brand brand1 = brandService.getBrandByName(userSession.getCompanyId(), brand.getName());
        if (brand1 != null && brand1.getId().intValue() != brand.getId().intValue()) {
            throw new BizzException(BizzException.error_code_invalid_params, "已存在名为【" + brand.getName() + "】的品牌");
        }

        Boolean result = brandService.updateBrand(brand);
        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 删除品牌
     * @param id 品牌id
     * @return HttpResponseBodyWrapper 封装操作标记（ true删除成功，false删除失败）
     * */
    @ResponseBody
    @DeleteMapping("/brand/{id}")
    public HttpResponseBodyWrapper deleteBrand(HttpServletRequest request, @PathVariable Integer id) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        Boolean result = brandService.deleteBrand(userSession.getCompanyId(), id);
        return new HttpResponseBodyWrapper(result);
    }
}
